package com.g8.pethospitallearnbackend.controller;

import cn.hutool.core.util.RandomUtil;
import com.g8.pethospitallearnbackend.entity.PasswordModify;
import com.g8.pethospitallearnbackend.entity.PasswordReset;
import com.g8.pethospitallearnbackend.entity.User;
import com.g8.pethospitallearnbackend.entity.UserForLogin;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.exception.NoDataException;
import com.g8.pethospitallearnbackend.service.UserService;
import com.g8.pethospitallearnbackend.utils.JWTUtil;
import com.g8.pethospitallearnbackend.utils.RedisUtil;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/self")
public class SelfInfoController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/{userId}")
    public User getUserInfoById(@PathVariable("userId") String userId){
        User user = userService.getUserById(userId);
        // 如果能查到，就返回数据
        if (user != null) return user;
        // 如果查不到，那就抛出“未查询到相关数据”的异常
        else throw new NoDataException();
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody UserForLogin userForLogin) {
        String userNameOrEmail = userForLogin.getUserNameOrEmail();
        String password = userForLogin.getPassword();
        log.info("用户名或邮箱：[{}]",userNameOrEmail);
        log.info("密码：[{}]",password);

        Map<String, Object> map = new HashMap<>();

        User userDB = userService.login(userNameOrEmail, password);
        Map<String,String> payload = new HashMap<>();
        //用户登录成功后的信息放入payload
        payload.put("userId",userDB.getUserId());
        payload.put("userName",userDB.getUserName());
        payload.put("userRole",userDB.getUserRole().toString());
        //生成JWT令牌
        String token = JWTUtil.generateToken(payload);
        map.put("state",true);
        map.put("token",token);
        map.put("msg","认证成功");

        // 再返回一下该用户的id
        map.put("user", userDB);
        //还要返回一下该用户是 管理员：0 / 实习生：1
        map.put("userRole", userDB.getUserRole());

        log.info("token: "+token);
        return map;

    }

    @GetMapping("/emailverify/{email}")
    public String sendEmailCode(@PathVariable("email") String email) {
//        return "邮箱验证码已发送，为" + userService.verifyEMail(email);
        userService.verifyEMail(email);
        return "邮箱验证码已发送";
    }
    @GetMapping("/newpassword/emailverify/{email}")
    public String sendEmailCodeToResetPassword(@PathVariable("email") String email) {
//        return "邮箱验证码已发送，为" + userService.sendMailCode(email);
        userService.sendMailCode(email);
        return "邮箱验证码已发送";
    }

    @PostMapping("/signin")
    public User register(@RequestBody User user) {
        return userService.register(user);
    }

    @PutMapping("/email")
    public User modifyEmail(@RequestBody User user) {
        return userService.modifyEmail(user);
    }

    @PutMapping("/password")
    public User modifyPassword(@RequestBody PasswordModify passwordModify) {
        return userService.modifyPassword(passwordModify);
    }

    @PutMapping("/newpassword")
    public User resetPassword(@RequestBody PasswordReset passwordReset) {
        return userService.resetPassword(passwordReset);
    }

    @GetMapping("/logout")
    public String logout( HttpServletRequest request) throws Exception {
//        String token = request.getHeader("token");
//        Object expTokenInRe = redisUtil.get("expiredToken");
//        if(expTokenInRe == null) {
//            List<String> expiredToken = new ArrayList<>();
//            expiredToken.add(token);
//            redisUtil.set("expiredToken", expiredToken);
//
////            for(String s : (List<String>) redisUtil.get("expiredToken")) log.info("beforDelToken:" + s);
//        }else {
//            List<String> expTokenInReStr = new ArrayList<>();
//            if (expTokenInRe instanceof ArrayList<?>) {
//                for (Object o : (List<?>) expTokenInRe) {
//                    expTokenInReStr.add((String) o);
//                }
//            }
//            expTokenInReStr.add(token);
//            redisUtil.set("expiredToken", expTokenInReStr, 7, TimeUnit.DAYS);
//        }
//        expTokenInRe = redisUtil.get("expiredToken");
//        if (expTokenInRe instanceof ArrayList<?>) {
//            for (Object o : (List<?>) expTokenInRe) {
//                log.info("Token:" + o);
//            }
//        }
        return "用户" + "已登出";
//        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "登出失败");
    }

    @PutMapping("")
    public User modifyOtherInfo(@RequestBody User user) {
        return userService.modifyInfo(user);
    }

}
